package com.example.iread.util;

import android.media.MediaPlayer;

import java.io.IOException;

public final class MediaPlayerUtil {

    public static MediaPlayer play(String url) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            // 设置DataSource
            mediaPlayer.setDataSource(url);
            // 准备异步播放
            mediaPlayer.prepareAsync();

            // 设置监听
            mediaPlayer.setOnPreparedListener(MediaPlayer::start);
            mediaPlayer.setOnCompletionListener(mp -> {
                if (mp != null) mp.release();
            });
            mediaPlayer.setOnErrorListener((mp, i, i2) -> {
                return false;
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return mediaPlayer;
    }

}
